/**
 * 删除 websites 集合中 domain 字段的唯一索引
 * 运行方式: node scripts/drop-domain-unique-index.js
 */

require('dotenv').config({ path: '.env.local' });
const { MongoClient } = require('mongodb');

async function dropDomainUniqueIndex() {
  // 从环境变量构建 MongoDB URI
  const host = process.env.MONGO_HOST || 'localhost';
  const port = process.env.MONGO_PORT || '27017';
  const database = process.env.MONGO_DATABASE || 'tracker';
  const username = process.env.MONGO_USERNAME;
  const password = process.env.MONGO_PASSWORD;
  
  let uri;
  if (username && password) {
    uri = `mongodb://${username}:${password}@${host}:${port}/${database}`;
  } else {
    uri = `mongodb://${host}:${port}/${database}`;
  }
  
  console.log(`Connecting to: mongodb://${host}:${port}/${database}`);
  const client = new MongoClient(uri);

  try {
    await client.connect();
    console.log('Connected to MongoDB');

    const db = client.db();
    const collection = db.collection('websites');

    // 获取当前索引
    const indexes = await collection.indexes();
    console.log('Current indexes:', indexes.map(idx => ({ name: idx.name, key: idx.key })));

    // 查找并删除 domain 的唯一索引
    const domainUniqueIndex = indexes.find(idx => 
      idx.key && idx.key.domain === 1 && idx.unique === true
    );

    if (domainUniqueIndex) {
      console.log(`Dropping unique index: ${domainUniqueIndex.name}`);
      await collection.dropIndex(domainUniqueIndex.name);
      console.log('✅ Domain unique index dropped successfully');
      
      // 重新创建普通索引
      await collection.createIndex({ domain: 1 });
      console.log('✅ Created new non-unique domain index');
    } else {
      console.log('ℹ️  No unique domain index found');
    }

    // 验证索引状态
    const newIndexes = await collection.indexes();
    const domainIndexes = newIndexes.filter(idx => idx.key && idx.key.domain === 1);
    console.log('Domain indexes after operation:', domainIndexes);

  } catch (error) {
    console.error('❌ Error:', error);
  } finally {
    await client.close();
    console.log('Disconnected from MongoDB');
  }
}

dropDomainUniqueIndex();
